package resource

import (
	"flare-admin/db/dao"
	"flare-admin/ecode"
	"flare-admin/http/model/k8sresource"
	"flare-admin/service/dto/k8s"
	"flare-admin/service/external/k8s/clientset"
	"strconv"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

type DeploymentService struct {
	dao *dao.DBTXQuery
}

func (s *DeploymentService) ListDeployments(ctx *gin.Context, csKey string, namespace string, kubeconfig []byte) ([]k8sresource.DeploymentInfo, error) {
	cs, err := clientset.GetClientset(csKey)
	if err != nil {
		if _, err = clientset.AddClientsetFromBytesByKey(csKey, kubeconfig); err != nil {
			logrus.Errorf("[ListDeployments] - 无法获取集群 %s 的Clientset: %v", csKey, err)
			return nil, err
		}
	}
	cs, err = clientset.GetClientset(csKey)
	if err != nil {
		return nil, ecode.ErrClusterNotExists
	}
	list, err := cs.AppsV1().Deployments(namespace).List(ctx, v1.ListOptions{})
	if err != nil {
		return nil, ecode.ErrClusterResourceFetching
	}

	deploymentInfoList := make([]k8sresource.DeploymentInfo, 0, len(list.Items))
	for _, deployment := range list.Items {
		model := k8s.TransferDeploymentToDeploymentModel(&deployment)
		deploymentInfoList = append(deploymentInfoList, *model)
	}
	return deploymentInfoList, nil
}

func (s *DeploymentService) ListDeploymentsByClusterID(ctx *gin.Context, clusterID string, namespace string) ([]k8sresource.DeploymentInfo, error) {
	id, err := strconv.ParseInt(clusterID, 10, 32)
	if err != nil {
		return nil, ecode.ErrRequestParam
	}
	clusterInfo, err := s.dao.Cluster.SelectSingleClusterConfigByID(ctx, int32(id))
	if err != nil {
		if ecode.IsBizError(err) {
			return nil, err
		}
		return nil, ecode.ErrClusterNotExists
	}
	return s.ListDeployments(ctx, clientset.BuildMapKey(clusterInfo.ClusterType, clusterInfo.Name), namespace, []byte(clusterInfo.Kubeconfig))
}
